package com.xd.lib.share;

import android.content.Context;
import android.graphics.Bitmap;

import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xd.lib.tool.util.BitmapUtil;

/**
 * 微信辅助类，用于微信分享
 * Created by Administrator on 2015/6/12.
 */
public class WeixinUtil {

    /**
     * appID（需要修改为通过审核的ID）
     */
    public static final String APP_ID = "wx96d406a3af36bf38";

    /**
     * 缩略图大小
     */
    private static final int THUMB_SIZE = 150;

    private IWXAPI api;

    private Context context;

    /**
     * 单例模式
     */
    private static WeixinUtil instance;

    private WeixinUtil(Context context){
        this.context = context;

        api = WXAPIFactory.createWXAPI(context, APP_ID, false);

        api.registerApp(APP_ID);
    }

    public static WeixinUtil getInstance(Context context){
        if (instance == null){
            instance = new WeixinUtil(context);
        }
        return instance;
    }

    /**
     * 发送文本信息到微信
     * @param text
     */
    public void sendText(String text){
        WXTextObject textObj = new WXTextObject();
        textObj.text = text;

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        msg.description = text;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "txt" + String.valueOf(System.currentTimeMillis());//transaction用于唯一标识一个请求
        req.message = msg;

        // SendMessageToWX.Req.WXSceneSession 发送至微信的会话中
        // SendMessageToWX.Req.WXSceneTimeLINE 发送至朋友圈
        req.scene = SendMessageToWX.Req.WXSceneTimeline;

        api.sendReq(req);
    }

    /**
     * 发图片到微信
     * @param bitmap
     */
    public void sendBitmap(Bitmap bitmap){
        WXImageObject imgObj = new WXImageObject(bitmap);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
        bitmap.recycle();
        msg.thumbData = BitmapUtil.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img"+String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;

        api.sendReq(req);
    }
}